package org.epidroid.epidroid.androsoul.ui.utils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.epidroid.epidroid.androsoul.engine.contacts.ContactGroup;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;

import android.app.Activity;

/*
 * Download the pictures of every contacts that does not already have one
 */
public class PicturesDownloader extends Thread {

	private List<NetsoulContact> _list = new ArrayList<NetsoulContact>();
	private Activity _context = null;
	private Runnable _onFinish = null;

	/*
	 * If true, the callback should be called once per contact for which the
	 * picture has been modified
	 */
	private Boolean _runOnFinishOneTimePerContact = false;

	public PicturesDownloader(Activity c, List<ContactGroup> groupList) {
		_context = c;

		// compute the list of contacts without any image
		Iterator<ContactGroup> it = groupList.iterator();
		while (it.hasNext()) {
			ContactGroup g = it.next();
			Iterator<NetsoulContact> itc = g.iterator();
			while (itc.hasNext()) {
				NetsoulContact contact = itc.next();
				if (contact.getImage(_context, false) == null)
					_list.add(contact);
			}
		}
	}

	/* Download pictures for one contact in particular */
	public PicturesDownloader(Activity c, NetsoulContact contact) {
		_context = c;
		_list.add(contact);
	}

	public boolean nothingToDownload() {
		return _list.isEmpty();
	}

	@Override
	public void run() {
		if (_list.isEmpty())
			return;

		for (NetsoulContact c : _list) {
			c.DownloadImage(_context);
			if (_runOnFinishOneTimePerContact && (_onFinish != null)) {
				_context.runOnUiThread(_onFinish);
			}
		}

		if (!_runOnFinishOneTimePerContact && _onFinish != null) {
			_context.runOnUiThread(_onFinish);
		}
	}

	public void set_onFinish(Runnable _onFinish, Boolean oneTimePerContact) {
		this._runOnFinishOneTimePerContact = oneTimePerContact;
		this._onFinish = _onFinish;
	}
}
